#include "login.h"
#include "ui_login.h"
#include "studentstore.h"
#include "utils.h"
#include "signin.h"
#include "init.h"
#include <QString>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <string.h>
#include <QMessageBox>
using namespace studentstore;
using namespace utils;

login::login(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::login) {
    ui->setupUi(this);
    showinfo = new show_stuinfo(this);
    showinfo->hide();
    signino = new signin();
    signino->hide();
    admin = new admin_interface(this);
    admin->hide();
    stu_interfaceUI = new stu_interface(this);
    stu_interfaceUI->hide();
    connect(this, SIGNAL(sendData(Student*, int)), admin, SLOT(getData(Student*, int)));
    connect(this, SIGNAL(sendData(Student*, int)), stu_interfaceUI, SLOT(getData(Student*, int)));
}

login::~login() {
    delete ui;
}

void login::on_loginButton_clicked() {

    QString str = ui->idEdit->text();
    string stu_id = string((const char *)str.toLocal8Bit());
    QString str2 = ui->pwdEdit->text();
    string code = string((const char*)str2.toLocal8Bit());
    //管理员type为0，用户的type为1
    if(stu_id.size() == 0) {
        QMessageBox::warning(this, "warning", "请输入账号");
        ui->idEdit->clear();
    } else if(code.size() == 0) {
        QMessageBox::warning(this, "warning", "请输入密码");
        ui->pwdEdit->clear();
    } else if(stu_id[0] == '#') {
        Student* stu = search_oneReturn<Student>("stu_id", stu_id, studentDatPath) ;
        if(strcmp(stu->pwdHash, (sha1(sha1(code.c_str()) + (string)(stu->pwdSalt))).data()) == 0) {
            emit sendData(stu, 0); //普通管理
            admin->open();
        } else {
            QMessageBox::warning(this, "warning", "账号或密码错误");
        }

    } else if(judge_user(stu_id) == -1) {
        QMessageBox::warning(this, "warning", "账号格式有误");
    }

    else {
        Student* stu = search_oneReturn<Student>("stu_id", stu_id, studentDatPath) ;
        if(strcmp(stu_id.c_str(), admin_id.c_str()) == 0 && strcmp(code.c_str(), admin_password.c_str()) == 0) {
            emit sendData(stu, 2); //超管
            admin->open();
        } else if(strcmp(stu->pwdHash, (sha1(sha1(code.data()) + (string)(stu->pwdSalt))).data()) == 0) {
            emit sendData(stu, 1); //普通用户
            stu_interfaceUI->open();
            addLog("[login] UserID[" + to_string(stu->ID) + "] login successfully");
        } else {
            QMessageBox::warning(this, "warning", "账号或密码有误");
        }
    }
}




void login::on_pushButton_clicked() {
    signino->show();
}
